<template>
  <div class="index-box">
    <div class="content-head">
      <a-row align="middle">
        <a-col span="14">
          <a-button type="primary" icon="plus" @click="() => { groupSetModal = true }">新增群组</a-button>
        </a-col>
      </a-row>
    </div>
    <div class="content-body">
      <a-table :columns="columns" rowKey="id" :pagination="pagination" :dataSource="dataSource" :loading="loading" @change="tableChange">
        <template slot="operation" slot-scope="text,record">
          <a-dropdown>
            <a class="ant-dropdown-link" href="javascript:void(0);">操作 <a-icon type="down" /></a>
            <a-menu slot="overlay" @click="operation($event,record)">
              <a-menu-item key="1">权限</a-menu-item>
              <a-menu-item key="2">编辑</a-menu-item>
              <a-menu-item key="3">删除</a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>
      </a-table>
    </div>
    <!-- 设置权限 -->
    <a-modal title="设置权限" destroyOnClose :visible="setGroupRoleModal" @cancel="() => { setGroupRoleModal = false; }">
      <template slot="footer">
        <a-button key="back" @click="() => { setGroupRoleModal = false; }">取消</a-button>
        <a-button type="primary" @click="setGroupRoleOk" :disabled="setGroupRoleModalLoading" :loading="setGroupRoleModalLoading">确定</a-button>
      </template>
      <div>
        <a-skeleton active :loading="treeLoading">
          <a-tree
            :treeData="treeData"
            checkable
            :checkedKeys="checkedKeys"
            @check="onCheck"
            @select="onSelect"
            :selectedKeys="selectedKeys"
          />
        </a-skeleton>
      </div>
    </a-modal>
    <!-- 添加or编辑群组弹窗 -->
    <a-modal title="群组设置" v-model="groupSetModal" :confirmLoading="groupSetModalConfirmLoading" :afterClose="afterCloseUnitModal" @ok="handleSubmit">
      <a-form :form="form" @submit="handleSubmit">
        <a-form-item label="群组名称" :labelCol="{xs:{span:24},sm:{span:6}}" :wrapperCol="{xs:{span:24},sm:{span:16}}">
          <a-input placeholder="请输入群组名称" v-decorator="['name',{rules:[{required:true,message:'群组名称不可为空'}],initialValue:''}]"></a-input>
        </a-form-item>
        <a-form-item label="描述" :labelCol="{xs:{span:24},sm:{span:6}}" :wrapperCol="{xs:{span:24},sm:{span:16}}">
          <a-input type="textarea" placeholder="请输入群组描述" :rows="4" v-decorator="['description',{initialValue:''}]"></a-input>
        </a-form-item>
        <a-form-item style="display: none;">
          <a-input type="hidden" v-decorator="['id',{initialValue:0}]"></a-input>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import { mapGetters } from 'vuex'
  export default {
    name: 'purview_group',
    data() {
      return {
        description:'管理组关联菜单权限',
        form:this.$form.createForm(this),
        token:this.$ls.get(ACCESS_TOKEN),
        setGroupRoleModal:false, // 确定
        setGroupRoleModalLoading:false, // 设置权限弹窗确认按钮状态
        treeLoading:true, // 权限节点展位图显示状态
        groupSetModal:false, // 添加or编辑群组弹窗
        groupSetModalConfirmLoading:false, // 添加or编辑群组弹窗确认按钮loading
        columns:[
          {
            title:'ID',
            dataIndex:'id'
          },
          {
            title:'群组名称',
            dataIndex:'name'
          },
          {
            title:'描述',
            dataIndex:'description'
          },
          {
            title:'操作',
            dataIndex:'operation',
            scopedSlots:{customRender:'operation'}
          }
        ],
        pagination:{}, // 表格分页
        dataSource:[], // 表格数据
        loading:false,
        groupInfo:{}, // 组数据
        treeData:[], // 权限列表
        checkedKeys: [], // 选中数据
        selectedKeys:[],
      }
    },
    mounted() {
      this.groupList();
    },
    methods:{
      ...mapGetters(['userInfo']),
      // 获取群组菜单
      groupList(page = 1) {
        this.loading = true;
        this.axios({
          method:'post',
          url:'/purview/groupList',
          data:{token:this.token,page}
        }).then(res => {
          Object.assign(res.data.info,{ hideOnSinglePage:true });
          this.pagination = res.data.info;
          this.dataSource = res.data.data;
          this.loading = false;
        }).catch(err => {
          this.loading = false;
          this.$message.error('服务器发生错误...',2);
        });
      },
      tableChange(pagination, filters, sorter) {
        this.groupList(pagination.current);
      },
      // 下拉菜单操作按钮
      operation({ key },info) {
        const _this = this;
        console.log(info)
        _this.groupInfo = info;
        if(key === '1') {
          this.getTreeData()
          this.setGroupRoleModal = true;
        }
        // 编辑
        if(key === '2'){
          this.groupSetModal = true;
          this.$nextTick(() => {
            _this.form.setFieldsValue({id:info.id,name:info.name,description:info.description});
          })
        }
        // 删除
        if(key === '3'){
          this.$confirm({
            title: `确定要删除\"${info.name}\"群组？`,
            content:'删除后将不可恢复',
            onOk() {
              return new Promise((resolve, reject) => {
                _this.axios({
                  method:'post',
                  url:'/purview/delGroup',
                  data:{token:_this.token,id:info.id},
                }).then(res => {
                  if(res.code === 0){
                    _this.$message.success(res.msg,2);
                    _this.groupList();
                    resolve();
                  }else reject(res.msg);
                }).catch(err => {
                  _this.$message.error('服务器发生错误...',2);
                })
              }).catch((msg) => _this.$message.error(msg,2));
            },
            onCancel() {},
          });
        }
      },
      // 添加or编辑群组提交
      handleSubmit() {
        this.form.validateFields((err, values) => {
          if (err) {
            for (let key in err) {
              for (let item of err[key]['errors']) return this.$message.warning(item['message'], 2);
            }
          }
          Object.assign(values,{token:this.token,pms_ar_id:this.userInfo().pms_ar_id})
          this.groupSetModalConfirmLoading = true;
          this.axios({
            method:'post',
            url:'/purview/operationGroup',
            data:values,
          }).then(res => {
            if(res.code === 0){
              this.$message.success(res.msg,2);
              this.groupSetModal = false;
              this.groupSetModalConfirmLoading = false;
              this.groupList();
            }else this.$message.error('服务器发生错误...',2);
          }).catch((err) => {
            this.$message.error('服务器发生错误...',2);
          })
        })
      },
      // 添加or编辑群组完全关闭
      afterCloseUnitModal() {
        this.form.resetFields();
        this.groupSetModalConfirmLoading = false;
      },
      // 获取权限组菜单
      getTreeData() {
        this.treeLoading = true;
        let roleArr = [1,2];
        if(this.groupInfo.menus) {
          console.log(this.groupInfo.menus)
          this.groupInfo.menus.split(',').forEach(item => roleArr.push(Number(item)));
        }
        this.axios({
          method:'post',
          url:'/purview/getTree',
          data:{token:this.token}
        }).then(res => {
          for(let item of res.data){
            item.key = item.id;
            if(item.id == 1) item.disabled = true;
            for(let value of item.children){
              value.key = value.id;
              if(value.id == 2) value.disabled = true;
              for(let values of value.children) values.key = values.id;
            }
          }
          this.treeData = res.data;
          this.checkedKeys = roleArr;
          this.treeLoading = false;
        }).catch((err) => {
          this.$message.error('服务器发生错误...',2);
        })
      },
      onSelect(selectedKeys, info) {
        this.selectedKeys = selectedKeys;
      },
      onCheck(checkedKeys) {
        console.log(checkedKeys)
        this.checkedKeys = checkedKeys
      },
      // 确定设置权限
      setGroupRoleOk() {
        this.setGroupRoleModalLoading = true;
        this.axios({
          method:'post',
          url:'/purview/setGroupPurview',
          data:{token:this.token,id:this.groupInfo.id,menus:this.checkedKeys.join(',')}
        }).then(res => {
          if(res.code === 0){
            this.$message.success(res.msg,2);
            this.groupList();
            this.setGroupRoleModal = false;
          }else this.$message.warning(res.msg,2);
        }).catch((err) => {
          this.$message.error('服务器发生错误...',2);
        }).finally(() => this.setGroupRoleModalLoading = false)
      }
    }
  }
</script>

<style lang="less" scoped>
  .index-box{
    background: #ffffff;
    padding: 25px;
    box-sizing: border-box;
    .content-body{
      padding-top:20px;
    }
  }
</style>